<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/6/11
 * Time: 20:15
 */

namespace common\models\Service;


use common\models\CommonFunction;
use common\models\CommonVar;
use common\models\DAO\DayAccrual;
use common\models\DAO\Region;
use common\models\DAO\User;
use common\models\DAO\UserCard;
use common\models\DAO\UserCashList;
use common\models\DAO\UserFreeze;
use common\models\DAO\UserWalletLog;
use common\models\LLpay\LLcashConfig;
use common\models\LLpay\LLcashSubmit;
use common\models\LLpay\LLpayConfig;
use common\msg\UserMsg;
use yii\base\Exception;

class UserCash {

    //用户id
    public $userID;
    public $poundage = 300;

    /**
     * @param array $userID 用户id
     */
    public function __construct($userID = null){
        if($userID)
            $this->userID = $userID;
    }

    public function init(){
        $userID = $this->userID;

        //判断用户是否设置
        $return['status'] = 0;
       /* $userInfo = \common\models\DAO\User::findOne($userID);
        if(empty($userInfo['dealPassword']) ){
            $return['status'] = 2;
            $return['msg'] = UserMsg::$set_password;
            return $return;
        }*/
        $result['status'] = 1;
        //获取用户银行卡号
        $bankCard = \common\models\DAO\UserCard::find()->where(array('userID'=>$userID))->orderBy('id desc')->one();
        if(!empty($bankCard['card'])){
            $cardInfo['card'] = substr(CommonFunction::decrypt($bankCard['card'], CommonVar::$encrypt), -4);
            //银行编码对应银行
            $bankCode = CommonVar::$bank_code;
            if(isset($bankCard['bankCode']) && isset($bankCode[$bankCard['bankCode']])){
                $cardInfo['bank_id'] = CommonFunction::encrypt($bankCard['id']);
                $cardInfo['bankCode'] = $bankCard['bankCode'];
                $cardInfo['bank'] = $bankCode[$bankCard['bankCode']]['name'];
            }else{
                $return['msg'] = UserMsg::$no_money;
                return $return;
            }
            $result['card'] = $cardInfo;
        }else{
            $return['status'] = 2;
            $return['msg'] = UserMsg::$no_money;
            return $return;
        }
        $no_bank = ['01020000', '01030000', '01040000', '03080000', '03030000', '03100000'];
        if(!in_array($cardInfo['bankCode'], $no_bank) && !$bankCard['branch']){
            $result['branch'] = 1;
        }


        $remainder = Wallet::can_remainder($userID);
        $result['money'] = $remainder;
        $result['user_money'] = CommonFunction::formatMoney($remainder);
        return $result;
    }

    public static function get($id, $userID){
        $userCash = \common\models\DAO\UserCash::findOne(['id'=>$id, 'userID'=>$userID]);
        if($userCash){
            $userCash = $userCash->attributes;
            return $userCash;
        }else
            return false;
    }
    /**
     * 提现调用外部接口
     * @param $param
     * @return array
     */
    public function complete($param , $source = 2){

        $return['status'] = 0;
        $return['msg'] = UserMsg::$time_out;
        $userID = intval($this->userID);
        $wind_check = WindControlService::check($userID);
        if(!$wind_check){
            $return['msg'] = UserMsg::$risk;
            return $return;
        }
        $bank_id = CommonFunction::decrypt($param['bank_id']);
        $blacklist = [3025,2886, 2825, 2886, 2865, 2853, 3912];
        if(in_array($userID, $blacklist))
            return $return;
        /*$invest_money = DayAccrual::find()->where("userID={$userID} and chargeID!=0")->sum('invest');
        $invest_money = intval($invest_money);*/

        $money_order = doubleval($param['money_order']);
        $poundage = $this->poundage;
        $user_money_order = intval($money_order * 100);

		/*if($user_money_order < 100000 && $user_money_order < $poundage){
            $return['msg'] = UserMsg::$no_poundage;
            return $return;
        }*/
        //校验用户信息
        $userModel = User::findOne($userID);
        if(!$userModel){
            $return['msg'] = UserMsg::$identity_error;
            return $return;
        }
        $user_info = $userModel->attributes;

        if(empty($user_info['identity'])){
            $return['msg'] = UserMsg::$identity_error;
            return $return;
        }

        // //校验交易密码
        // $cash_password = CommonFunction::encryptPassword($param['cash_password'], $user_info['encrypt']);
        // if($cash_password != $param['dealPassword']){
            // $return['msg'] = UserMsg::$deal_password_error;
            // return $return;
        // }

        //校验用户余额
        $remainder = Wallet::can_remainder($userID);
        if(!$remainder){
            $return['msg'] = UserMsg::$no_money;
            return $return;
        }
        if($user_money_order > $remainder){
            $return['msg'] = UserMsg::$no_money;
            return $return;
        }
        if($user_money_order < 10000){
            $return['msg'] = '最少提现金额100元！';
            return $return;
        }
       /* if($invest_money < 10000){
            return $return;
        }*/

        //校验银行卡
        $cardModel = UserCard::findOne(array('id'=>$bank_id, 'userID'=>$userID));
        if(!$cardModel){
            $return['msg'] = UserMsg::$bank_card_error;
            return $return;
        }
        $card_info = $cardModel->attributes;

        $no_bank = ['01020000', '01030000', '01040000', '03080000', '03030000', '03100000'];
        if(!in_array($card_info['bankCode'], $no_bank)){
            if(!$card_info['branch'] && (empty($param['branch']) || empty($param['city']))){
                $return['msg'] = UserMsg::$branch_error;
                return $return;
            }
            if(!$card_info['branch']){
                /*if(!strpos($param['city'], "市") && !strpos($param['city'], "州")){
                    !strpos($param['city'], "市") && $param['city'] = $param['city'].'市';
                }*/
                $municipality = '北京市天津市上海市重庆市';
                $regionType = 2;
                strstr($municipality, $param['city']) && $regionType = 1;
                $directly = '石河子市';
                strstr($directly, $param['city']) && $regionType = 3;
                $city = Region::find()->asArray()->where('regionType='.$regionType)->andFilterWhere(['like', 'regionName', $param['city']])->one();
                if(!$city){
                    $return['msg'] = UserMsg::$branch_city;
                    return $return;
                }
                $card_info['cityCode'] = $city['regionCode'];
                $province = Region::findOne($city['parentID']);
                if(!$province){
                    $return['msg'] = UserMsg::$branch_city;
                    return $return;
                }
                $card_info['provinceCode'] = $province['regionCode'];
                $card_info['branch'] = $param['branch'];
            }
        }




        $now = time();
        $transaction = \Yii::$app->db->beginTransaction();
        $order_no = 'T'.CommonFunction::buildOrder();
        //添加提现记录
        $userCash = new \common\models\DAO\UserCash();
        $userCash->bankCard = $card_info['card'];
        $userCash->userID = $userID;
        $userCash->money = $user_money_order;
        $userCash->order = $order_no;
        $userCash->createTime = $now;
        $cash_result = $userCash->save();
        if(!$cash_result){
            $transaction->rollBack();
            return $return;
        }

        $date = intval(date('Ymd'));
        //扣除账户余额
        $accrual = DayAccrual::find()->where(['userID'=>$userID])->andWhere("money > 0 and ((chargeID != 0 AND date < $date) OR chargeID=0) AND sendID=0 and typeID!=5")->orderBy('date asc')->all();
        $init_money = $user_money_order;
        foreach($accrual as $v){
            $money = intval($v['money']);
            $id = $v['id'];
            if($money <= 0)
                continue;
            if($money < $init_money){
                $accrual_one = DayAccrual::findOne($id);
                $accrual_one->money = 0;
                $accrual_one->updateTime = $now;
                $one_result = $accrual_one->save();
                if(!$one_result){
                    $transaction->rollBack();
                    return $return;
                }
                //提现明细
                $cash_list = new UserCashList();
                $cash_list->userID = $userID;
                $cash_list->money = $money;
                $cash_list->createTime = $now;
                $cash_list->accrualID = $id;
                $cash_list->cashID = $userCash['id'];
                $cash_list_result = $cash_list->save();
                if(!$cash_list_result){
                    $transaction->rollBack();
                    return $return;
                }
                $init_money = $init_money - $money;
            }else{
                $accrual_one = DayAccrual::findOne($id);
                $accrual_one->money = $money - $init_money;
                $accrual_one->updateTime = $now;
                $one_result = $accrual_one->save();
                if(!$one_result){
                    $transaction->rollBack();
                    return $return;
                }
                $cash_list = new UserCashList();
                $cash_list->userID = $userID;
                $cash_list->money = $init_money;
                $cash_list->createTime = $now;
                $cash_list->accrualID = $id;
                $cash_list->cashID = $userCash['id'];
                $cash_list_result = $cash_list->save();
                if(!$cash_list_result){
                    $transaction->rollBack();
                    return $return;
                }
                break;
            }
        }
        //钱包明细
        $user_wallet = new UserWalletLog();
        $user_wallet->type = 2;
        $user_wallet->cashID = $userCash['id'];
        $user_wallet->money = $user_money_order;
        $user_wallet->createTime = $now;
        $user_wallet->userID = $userID;
        $user_wallet->road = 1;
        $user_wallet_result = $user_wallet->save();
        if(!$user_wallet_result){
            $transaction->rollBack();
            return $return;
        }

        //更新用户账号冻结余额
        $freezeModel = UserFreeze::findOne($userID);
        if(!$freezeModel){
            $freezeModel = new UserFreeze();
            $freezeModel->userID = $userID;
            $freezeModel->money = $user_money_order;
            $freezeModel->updateTime = $now;
            $freeze_result = $freezeModel->save();
        }else{
            $freeze_info = $freezeModel->attributes;
            $freezeModel->money = intval($freeze_info['money']) + $user_money_order;
            $freezeModel->updateTime = $now;
            $freeze_result = $freezeModel->save();
        }
        if(!$freeze_result  ){
            $transaction->rollBack();
            return $return;
        }

        /**************************请求参数**************************/
        //三块钱手续费
       // $user_money_order < 100000 && $user_money_order = $user_money_order - $poundage;
        //必填

        //商品名称
        $no_order = $order_no;

        //订单时间
        $dt_order = date('YmdHis', $now);
        $flag_card = '0';
        $card_no = CommonFunction::decrypt($card_info['card'], CommonVar::$encrypt);
        $acct_name = $user_info['realName'];
        $info_order = UserMsg::$cash;
        $notify_url = LLcashConfig::$notify_url;
        $api_version = LLcashConfig::$api_version;



        //退款地址
        $llpay_gateway_new = 'https://yintong.com.cn/traderapi/cardandpay.htm';
        //需http://格式的完整路径，不能加?id=123这类自定义参数

        /************************************************************/

        $llpay_config = LLcashConfig::getConfig();
        //构造要请求的参数数组，无需改动
        $parameter = array (
            "oid_partner" => trim($llpay_config['oid_partner']),
            "sign_type" => trim('RSA'),
            "no_order" => $no_order,
            "dt_order" => $dt_order,
            "money_order" => $user_money_order/100,
            "flag_card" => $flag_card,
            "card_no" => $card_no,
            "acct_name" => $acct_name,
            "info_order" => $info_order,
            "notify_url" => $notify_url,
            "api_version" => $api_version,
        );
        if($card_info['branch']){
            $parameter['province_code'] =  $card_info['provinceCode'];
            $parameter['city_code'] =  $card_info['cityCode'];
            $parameter['brabank_name'] =  $card_info['branch'];
        }
        $llpay_config['sign_type'] = trim('RSA');
        //建立请求
        $llpaySubmit = new LLcashSubmit($llpay_config);
        $html_text = json_decode($llpaySubmit->buildRequestJSON($parameter,$llpay_gateway_new), true);
        if($source !== 2){

        }
        if($html_text['ret_code'] == '0000'){
            if(isset($param['openID'])){
                SendWxMessage::cashNotice($param['openID'], $user_money_order);
            }
            if($card_info['branch']){
                $cardModel->provinceCode = $card_info['provinceCode'];
                $cardModel->cityCode = $card_info['cityCode'];
                $cardModel->branch = $card_info['branch'];
                $cardModel->save();
            }
            $transaction->commit();
            $now_day = strtotime(date('Ymd'));
            $cash_sum = intval(\common\models\DAO\UserCash::find()->where("createTime>=$now_day and (status=1 or status=2)")->sum('money'));
            if($cash_sum >= 10000000){
                CommonFunction::sendCode('13165753886,18700638606,18629666633,15829704545,15389185181,15384609230','今日'.date('Y-m-d').'提现额度已达'.CommonFunction::formatMoney($cash_sum).'元，请登录后台查看明细：http://120.55.176.253:8080/');
            }
            return ['status'=>1, 'url'=> \Yii::$app->urlManager->createUrl(['cash/info', 'id' => $userCash->id]),'id' => $userCash->id];
        }else{
            $transaction->rollBack();
            LLpayConfig::llPayLog('用户id：'.$userID.'提现失败！错误原因：'.$html_text['ret_msg']);
            CommonFunction::sendCode('13165753886,18700638606,18629666633,15829704545,15389185181,15384609230,18202918866',
                $user_info['realName'].'【'.CommonFunction::decrypt($user_info['phone']).'】'.'提现'.CommonFunction::formatMoney($user_money_order).'元失败，原因：'.$html_text['ret_msg']);
            $return['msg'] = '提现失败！请联系客服'.\Yii::$app->params['tel'];
            return $return;
        }
    }

    public function notice($no_order, $result_pay, $sourceID = 1){
        $return['status'] = 0;
        $return['msg'] = UserMsg::$time_out;
        $cashModel = \common\models\DAO\UserCash::findOne(array('order'=>$no_order));
        if(!$cashModel){
            $return['msg'] = UserMsg::$call_center;
            return $return;
        }
        if($cashModel['status'] !== 2){
            $return['status'] = 1;
            return $return;
        }
        $cash_info = $cashModel->attributes;
        $userID = $cash_info['userID'];
        $userInfo = User::findOne($userID);
        if(!$userInfo)
            return $return;
        $cash_money = intval($cash_info['money']);
        $freezeModel = UserFreeze::findOne($userID);

        if(!$freezeModel){
            $return['msg'] = UserMsg::$call_center;
            return $return;
        }

        $freeze_info = $freezeModel->attributes;
        $freeze_money = intval($freeze_info['money']);
        if($cash_money > $freeze_money){
            return array('status'=>0, 'msg'=>UserMsg::$call_center);
        }
        $now = time();
        $transaction = \Yii::$app->db->beginTransaction();
        try{
            if($result_pay == 'SUCCESS'){
                //更新提现状态
                $cashModel->status = 1;
                $cashModel->updateTime = $now;
                $cash_result = $cashModel->save();
                if(!$cash_result){
                    $transaction->rollBack();
                    return $return;
                }
               /* if($cash_money < 100000){
                    $poundage = $this->poundage;
                    $poundage_money = $poundage;
                    //手续费列表
                    $poundage = new UserPoundage();
                    $poundage->cashID = $cashModel->id;
                    $poundage->userID = $userID;
                    $poundage->money = $cash_money;
                    $poundage->poundage = $poundage_money;
                    $poundage->createTime = time();
                    $poundage_result = $poundage->save();
                    if(!$poundage_result){
                        $transaction->rollBack();
                        return $return;
                    }
                }*/
                if(!empty($userInfo['openID'])){
                    SendWxMessage::cash($userInfo['openID'], CommonFunction::formatMoney($cash_money), CommonFunction::dealBankCard($cash_info['bankCard']));
                }
                //用户日志
                $user_log = UserLog::set(['userID'=>$userID, 'money'=> $cash_money,
                    'investID'=>$cashModel['id'], 'sourceID'=>$sourceID, 'desc'=>'提现']);
                if(!$user_log){
                    $transaction->rollBack();
                    return $return;
                }
                //更新冻结资金状态
                $freezeModel->money = $freeze_money - $cash_money;
                $freezeModel->updateTime = $now;
                $freeze_result = $freezeModel->save();
                if(!$freeze_result){
                    $transaction->rollBack();
                    return $return;
                }
            }else{
                //更新提现状态
                $cashModel->status = 0;
                $cashModel->updateTime = $now;
                $cash_result = $cashModel->save();
                if(!$cash_result){
                    $transaction->rollBack();
                    return $return;
                }
                $userCard = UserCard::findOne(['userID'=>$userID]);
                if(!empty($userCard['branch'])){
                    $userCard->provinceCode = '';
                    $userCard->cityCode = '';
                    $userCard->branch = '';
                    $userCard->save();
                    $userCard_result = $userCard->save();
                    if(!$userCard_result){
                        $transaction->rollBack();
                        return $return;
                    }
                }
                //更新冻结资金余额
                $freezeModel->money = $freeze_money - $cash_money;
                $freezeModel->updateTime = $now;
                $freeze_result = $freezeModel->save();
                if(!$freeze_result){
                    $transaction->rollBack();
                    return $return;
                }
                //钱包明细
                $user_wallet = new UserWalletLog();
                $user_wallet->type = 1;
                $user_wallet->cashID = $cash_info['id'];
                $user_wallet->money = $cash_money;
                $user_wallet->createTime = $now;
                $user_wallet->userID = $userID;
                $user_wallet->road = 6;
                $user_wallet_result = $user_wallet->save();
                if(!$user_wallet_result){
                    $transaction->rollBack();
                    return $return;
                }
                //更新用户账号余额
                $date = date('Ymd');
                $dayAccrual = new DayAccrual();
                $dayAccrual->userID = $userID;
                $dayAccrual->date = $date;
                $dayAccrual->money = $cash_money;
                $dayAccrual->invest = $cash_money;
                $dayAccrual->cashID = $cashModel->id;
                $dayAccrual->createTime = $now;
                $dayAccrual->updateTime = $now;
                $dayAccrual->typeID = 6;
                $accrual_result  = $dayAccrual->save();
                if(!$accrual_result){
                    $transaction->rollBack();
                    return $return;
                }
            }
            $transaction->commit();
            return ['status'=>1];
        }catch (Exception $e){
            $transaction->rollBack();
            return $return;
        }
    }

    /*
     * 提现列表
     */
    public static function getList($userID, $page = 1, $limit = 10){
        if($page <= 0)
            $page = 1;
        if($limit <= 0)
            $limit = 10;
        $start = (intval($page) - 1) * $limit;
        $list = \common\models\DAO\UserCash::find()->where(['userID'=>$userID])->asArray()->limit($limit)
            ->offset($start)->orderBy('id desc')->all();
        $result = [];
        foreach($list as $k=>$v){

            $_list['createTime'] = date('Y-m-d H:i', $v['createTime']);
            $_list['money'] = CommonFunction::formatMoney($v['money']);
            $status = '处理中';
            $v['status'] == 0 && $status = '提现失败';
            $v['status'] == 1 && $status = '提现成功';
            $v['status'] == 2 && $status = '提现中';
            $_list['info'] = $status;
            $_list['status'] = $v['status'];
            $result[] = $_list;
        }
        return $result;
    }

}